package com.f6.weixin.qiantai.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.f6.exceptions.BusinessException;
import com.f6.service.CommonService;
import com.f6.utils.SystemConstans;
import com.f6.vo.DBParameter;
import com.f6.weixin.utils.CommonUtil;
import com.f6.weixin.utils.ConfigUtil;
import com.f6.weixin.utils.PayCommonUtil;
import com.f6.weixin.utils.XMLUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping(SystemConstans.PAY_TEST)
public class PayController {
	@Autowired
	private CommonService commonservice;

	///
	private Logger logger = LoggerFactory.getLogger(PayController.class);

	/// 获取权限验证配置
	@RequestMapping(value = "pay", method = RequestMethod.GET)
	public ModelAndView pay(HttpServletRequest request, HttpServletResponse response) {
		logger.info("---enter pay-------");
		String code = request.getParameter("code");
		String openid = request.getParameter("openid");
		String orderCode = request.getParameter("ordercode");
		String totalPrice = request.getParameter("totalprice");

		logger.info("---code-------" + code);
		logger.info("---openid-------" + openid);
		logger.info("--orderCode-------" + orderCode);
		ModelAndView mv = new ModelAndView();
		mv.addObject("code", code);
		mv.addObject("openid", openid);
		mv.addObject("ordercode", orderCode);
		mv.addObject("totalprice", totalPrice);
		mv.setViewName("qt/pay1");
		return mv;

	}

	///
	/// 获取权限验证配置
	@RequestMapping(value = "payconfig", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getPayConfig(HttpServletRequest request, HttpServletResponse response) throws JDOMException, IOException {
		logger.info("+++++++++++++++++++enter getPayConfig ");
		String openid = request.getParameter("openid");
		String ordercode = request.getParameter("ordercode");
		String totalprice = request.getParameter("totalprice");

		SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
		parameters.put("appid", ConfigUtil.APPID);
		parameters.put("mch_id", ConfigUtil.MCH_ID);
		parameters.put("nonce_str", PayCommonUtil.CreateNoncestr());
		parameters.put("body", "LEO测试");
		parameters.put("out_trade_no", ordercode);// 商家订单号
		parameters.put("total_fee", "1");// 以分为单位
		parameters.put("spbill_create_ip", request.getRemoteAddr());
		parameters.put("notify_url", ConfigUtil.NOTIFY_URL);
		parameters.put("trade_type", "JSAPI");
		parameters.put("openid", openid);
		String sign = PayCommonUtil.createSign("UTF-8", parameters);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		logger.info("--&&----requestXML-------" + requestXML);
		String result = CommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		
		logger.info("--&&----result-------" + result);
		Map<String, String> map = XMLUtil.doXMLParse(result);
		logger.info("--&&----map-------" + map);
		
		String json = "";
		if (map != null) {
			SortedMap<Object, Object> params = new TreeMap<Object, Object>();
			params.put("appId", SystemConstans.APPID);
			params.put("timeStamp", Long.toString(new Date().getTime()));
			params.put("nonceStr", PayCommonUtil.CreateNoncestr());
			params.put("package", "prepay_id=" + map.get("prepay_id"));
			params.put("signType", ConfigUtil.SIGN_TYPE);
			String paySign = PayCommonUtil.createSign("UTF-8", params);
			params.put("packageValue", "prepay_id=" + map.get("prepay_id")); // 这里用packageValue是预防package是关键字在js获取值出错
			params.put("paySign", paySign); // paySign的生成规则和Sign的生成规则一致
			params.put("sendUrl", ConfigUtil.SUCCESS_URL); // 付款成功后跳转的页面
			String userAgent = request.getHeader("user-agent");
			char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger") + 15);
			params.put("agent", new String(new char[] { agent }));// 微信版本号，用于前面提到的判断用户手机微信的版本是否是5.0以上版本。
			json = JSONObject.fromObject(params).toString();

			logger.info("------getPayConfig-------" + json);
		}

		return json;
	}

	/// 获取权限验证配置
	@RequestMapping(value = "paysuccess", method = RequestMethod.GET)
	@ResponseBody
	public void paySuccess(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException, BusinessException {
		logger.info("+++++++++++++++++++enter paysuccess ");
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
		outSteam.close();
		inStream.close();
		String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
		Map<Object, Object> map = XMLUtil.doXMLParse(result);
		for (Object keyValue : map.keySet()) {
			logger.info(keyValue + "=" + map.get(keyValue));
		}
		if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
			// TODO 对数据库的操作
			response.getWriter().write(PayCommonUtil.setXML("SUCCESS", "")); // 告诉微信服务器，我收到信息了，不要在调用回调action了

			logger.info("-------------" + PayCommonUtil.setXML("SUCCESS", ""));

			Map paramap = new HashMap<String, String>();
			paramap.put("orderCode", "");
			paramap.put("orderStatus", "已付款");
			DBParameter dbparam = new DBParameter();
			dbparam.setAction("updateOrderStatus");
			dbparam.setModule("putong.Order");
			dbparam.setParameter(paramap);
			commonservice.change(dbparam, SystemConstans.CHANGE_ACTION_UPDATE);
		}
	}

	@RequestMapping(value = "payfailed", method = RequestMethod.GET)
	public String payFailed(HttpServletRequest request, HttpServletResponse response) {
		logger.info("+++++++++++++++++++enter payFailed ");
		return "";
	}
	///

	/// 获取支付请求参数
	///

	///
	///
	public Map GetPaySign(int trade) {
		return null;
	}
}
